program imputesk 

syntax varname [if] [in] , id(varname) 

** gen two vars - 1. N used for imputation (-1 for non-imputed values) 
**				  2. imputed variable 	
 
set seed 345

gen nonmissing = (`1'!=.) 
qui su nonmissing 

sort nonmissing `id' 
global Nmissing = r(N) - r(sum) 
gen dv`1'_N = r(sum) 
gen dv`1' = .

forv i = 1/$Nmissing { 
capture drop rand 
qui gen rand = uniform() if nonmissing==1 
qui su rand 
qui su `1' if rand==r(min) 
qui replace dv`1' = r(mean) if _n==`i' 
}

replace dv`1'_N = -1  if nonmissing==1 
replace dv`1' = `1' if nonmissing==1 

drop nonmissing

end
